package net.uhuijia.utils;

import net.sf.json.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.*;

public class InputStreamUpload {

    public static JSONObject upload(String filePath,Integer fileName) throws IOException {
        //后台生成图片上传到服务器
        //创建HttpClient对象
        String results = "";
        String body = null;
        CloseableHttpClient client = HttpClients.createDefault();
        InputStream inputStream = new FileInputStream(filePath);
        HttpPost post = new HttpPost("https://www.uhuijia.com.cn/image-server/uploadImage/oss");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        //第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了
        //第三个参数是文件名
        //3)
        builder.addBinaryBody("uploadFile", inputStream, ContentType.create("multipart/form-data"), fileName+".jpg");
        //4)构建请求参数 普通表单项
        StringBody stringBody = new StringBody("12",ContentType.MULTIPART_FORM_DATA);
        builder.addPart("id",stringBody);
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        //发送请求
        HttpResponse response = client.execute(post);
        entity = response.getEntity();
        if (entity != null) {
            inputStream = entity.getContent();
            //转换为字节输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Consts.UTF_8));
            while ((body = br.readLine()) != null) {
                results = results + body;
                System.out.println(body);
            }
        }
        return  JSONObject.fromObject(results);
    }

    /**
     * 删除本地文件
     * @param filePath
     */
    public static void deleteLocalFile(String filePath){
        File f = new File(filePath);
        if(f.isFile()){
            f.delete();
        }else{
            System.out.println("Sorry,No such file");
        }
    }
}
